package cn.moefly.common.utils;

import org.yaml.snakeyaml.Yaml;

import java.util.Map;
import java.util.WeakHashMap;

public abstract class YamlUtils {

    private static WeakHashMap<String,Map<String,?>> sYamlWeakMap = new WeakHashMap<>();


    @SuppressWarnings("unchecked")
    public static <T> T readProperties(String yamlName, String paramName){
        Map<String,?> yamlRoot = loadOrCache(yamlName);
        return (T) getYamlProperties(yamlRoot,paramName);
    }

    private static Map<String,?> loadOrCache(String yamlName){
        return sYamlWeakMap.computeIfAbsent(yamlName, k->{
            Yaml yaml = new Yaml();
            Map<String,?> load = yaml.load(SystemEnvironmentUtils.resourceConfigFileInputStream(yamlName,false));
            synchronized (sYamlWeakMap){
                sYamlWeakMap.put(yamlName,load);
            }
            return load;
        });
    }

    private static Object getYamlProperties(Map yamlMap, String name){
        var firstIndexOfDot = name.indexOf('.');
        String currentName = name;
        String remainingName = null;
        if (firstIndexOfDot > 0){
            currentName = name.substring(0,firstIndexOfDot);
            remainingName = name.substring(firstIndexOfDot + 1);
        }
        Object currentLayerData = yamlMap.get(currentName);
        if (currentLayerData instanceof Map && remainingName!= null){
            return getYamlProperties((Map) currentLayerData,remainingName);
        } else {
            return currentLayerData;
        }
    }
}
